package com.xywl.escort.view.treasure;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.xywl.escort.R;
import com.xywl.escort.adapter.TreasureAdapter;
import com.xywl.escort.base.BaseFragment;
import com.xywl.escort.bean.BaseResp;
import com.xywl.escort.bean.ShoppingCartReq;
import com.xywl.escort.bean.ShoppingCartResp;
import com.xywl.escort.bean.ShoppingCartUpdateReq;
import com.xywl.escort.bean.ShoppingCartUpdateResp;
import com.xywl.escort.utils.NetworkUtil;
import com.xywl.escort.utils.NumberFormatUtils;
import com.xywl.escort.utils.ToastUtil;
import com.xywl.escort.widget.CustomDialog;
import com.xywl.escort.widget.HorizontalDividerItemDecoration;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import dagger.android.support.AndroidSupportInjection;
import qiu.niorgai.StatusBarCompat;
import timber.log.Timber;

public class TreasureFragment extends BaseFragment implements TreasureContract.View, SwipeRefreshLayout.OnRefreshListener {
    private static final String ARG_PARAM1 = "param1";
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_title_right)
    TextView mTvTitleRight;
    @BindView(R.id.recycler_treasure)
    RecyclerView mRecyclerTreasure;
    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.check_select_all)
    CheckBox mCheckSelectAll;

    @BindView(R.id.text_total_num)
    TextView mTextTotalNum;
    @BindView(R.id.text_total_price)
    TextView mTextTotalPrice;

    @Inject
    TreasureContract.Presenter mPresenter;

    private TreasureAdapter mAdapter;

    private CustomDialog mDialog;

    private List<ShoppingCartResp.DataBean> mList = new ArrayList<>();

    public TreasureFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        AndroidSupportInjection.inject(this);
        super.onAttach(context);
    }

    public static TreasureFragment newInstance(String param1) {
        TreasureFragment fragment = new TreasureFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_treasure;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        mTvTitle.setText(R.string.tab_treasure);
        if (null != this.getActivity()) {
            StatusBarCompat.translucentStatusBar(getActivity(), true);
        }

        mTvTitleRight.setText(R.string.shopping_delete);
        mTvTitleRight.setVisibility(View.VISIBLE);
        showText("合   计: 0.00元 (含运费: 0.00元)", "共0件商品 ");
        LinearLayoutManager manager = new LinearLayoutManager(this.getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        Paint paint = new Paint();
        paint.setStrokeWidth(20);
        if (null != this.getActivity()) {
            paint.setColor(ContextCompat.getColor(this.getActivity(), R.color.line_color));
            paint.setAntiAlias(true);
            mRecyclerTreasure.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this.getActivity()).paint(paint).build());
            mRecyclerTreasure.setLayoutManager(manager);
        }

        mAdapter = new TreasureAdapter(R.layout.item_treasure, mList);
        mRecyclerTreasure.setAdapter(mAdapter);

        View emptyView = LayoutInflater.from(this.getActivity()).inflate(R.layout.layout_empty_view, null);
        TextView tvEmpty = emptyView.findViewById(R.id.tv_empty);
        tvEmpty.setText(R.string.no_commodity_prompt);
        mAdapter.setEmptyView(emptyView);

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ShoppingCartResp.DataBean dataBean = mList.get(position);
                switch (view.getId()) {
                    case R.id.image_check: {
                        dataBean.isClick = !dataBean.isClick;
                        mAdapter.notifyDataSetChanged();
                        updateBottomBarAndCheck();
                    }
                    break;
                    case R.id.image_delete: {
                        delete(dataBean, position);
                        break;
                    }
                    case R.id.image_increase: {
                        if (null != TreasureFragment.this.getActivity()) {
                            if (!NetworkUtil.isAvailable(TreasureFragment.this.getActivity())) {
                                ToastUtil.showTip(TreasureFragment.this.getActivity(), R.string.network_error);
                                return;
                            }
                        }
                        increase(dataBean);
                    }
                    break;
                    case R.id.image_decrease: {
                        if (null != TreasureFragment.this.getActivity()) {
                            if (!NetworkUtil.isAvailable(TreasureFragment.this.getActivity())) {
                                ToastUtil.showTip(TreasureFragment.this.getActivity(), R.string.network_error);
                                return;
                            }
                        }
                        decrease(dataBean, position);
                    }
                    break;
                    case R.id.content: {
                        if (null != TreasureFragment.this.getActivity()) {
                            if (!NetworkUtil.isAvailable(TreasureFragment.this.getActivity())) {
                                ToastUtil.showTip(TreasureFragment.this.getActivity(), R.string.network_error);
                                return;
                            }
                        }
                        String spuId = dataBean.spuId;
                        String skuId = dataBean.skuId;
                        ARouter.getInstance()
                                .build("/xy/product/detail")
                                .withString("spuId", spuId)
                                .withString("skuId", skuId)
                                .navigation();
                    }
                    break;
                    default:
                        break;
                }
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.aid_prompt_color, R.color.colorBackground);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.takeView(this);
        ShoppingCartReq req = new ShoppingCartReq();
        mPresenter.loadTreasureList(req);
        mCheckSelectAll.setChecked(false);
        showText("合   计: 0.00元 (含运费: 0.00元)", "共0件商品 ");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            Timber.e("TreasureFragment onHiddenChanged hidden");
        } else {
            Timber.e("TreasureFragment onHiddenChanged");
            mPresenter.takeView(this);
            ShoppingCartReq req = new ShoppingCartReq();
            mPresenter.loadTreasureList(req);
            mCheckSelectAll.setChecked(false);
        }
    }

    @OnClick({R.id.tv_title_right, R.id.tv_submit, R.id.check_select_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_title_right: {
                batchDelete();
            }
            break;
            case R.id.tv_submit: {
                submitOrder();
            }
            break;
            case R.id.check_select_all: {
                selectAll();
            }
            break;
            default:
                break;
        }
    }

    private void increase(ShoppingCartResp.DataBean bean) {
        int num = bean.stock;
        BigDecimal bigDecimal = new BigDecimal("1");
        if (num >= 0) {
            if (bean.amount.intValue() >= num) {
                ToastUtil.showTip(TreasureFragment.this.getActivity(), R.string.shopping_inventory_shortage);
            } else {
                bean.amount = bean.amount.add(bigDecimal);
                updateShopCart(bean);
                mAdapter.notifyDataSetChanged();
                updateBottomBarAndCheck();
            }
        } else {
            bean.amount = bean.amount.add(bigDecimal);
            updateShopCart(bean);
            mAdapter.notifyDataSetChanged();
            updateBottomBarAndCheck();
        }
    }

    private void decrease(ShoppingCartResp.DataBean bean, final int position) {
        if (bean.amount.intValue() > 1) {
            BigDecimal bigDecimal = new BigDecimal("1");
            bean.amount = bean.amount.subtract(bigDecimal);
            updateShopCart(bean);
            mAdapter.notifyDataSetChanged();
            updateBottomBarAndCheck();
        } else if (bean.amount.intValue() == 1) {
            String skuId = bean.skuId;
            mPresenter.delShoppingCart(skuId, position);
            mAdapter.notifyDataSetChanged();
        } else {
            ToastUtil.showTip(TreasureFragment.this.getActivity(), "受不了了，宝贝不能再减少了哦");
        }
    }

    private void updateShopCart(ShoppingCartResp.DataBean commodityBean) {
        if (commodityBean.amount.intValue() > 0) {
            ShoppingCartUpdateReq bean = new ShoppingCartUpdateReq();
            bean.skuId = commodityBean.skuId;
            bean.amount = commodityBean.amount;
            mPresenter.updateShopCart(bean);
        }
    }

    private void delete(final ShoppingCartResp.DataBean dataBean, final int position) {
        mDialog = new CustomDialog.Builder(TreasureFragment.this.getActivity())
                .setMessage(R.string.shopping_delete_prompt)
                .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mDialog.dismiss();

                        String skuId = dataBean.skuId;
                        mPresenter.delShoppingCart(skuId, position);
                    }
                }).setPositiveButton(R.string.cancel, R.drawable.button_dialog_transparent, R.color.main_body_major_color, null).create();
        mDialog.show();
    }

    private void batchDelete() {
        boolean isSelect = false;
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).isClick) {
                isSelect = true;
            }
        }
        if (isSelect) {
            mDialog = new CustomDialog.Builder(TreasureFragment.this.getActivity())
                    .setMessage(R.string.shopping_delete_prompt)
                    .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int var2) {
                            mDialog.dismiss();
                            Iterator<ShoppingCartResp.DataBean> iterator = mList.iterator();
                            StringBuilder stringBuilder = new StringBuilder();
                            while (iterator.hasNext()) {
                                ShoppingCartResp.DataBean bean = iterator.next();
                                if (bean.isClick) {
                                    stringBuilder.append(bean.skuId);
                                    stringBuilder.append(",");
                                }
                            }
                            Timber.tag("TreasureFragment").e("skuId=" + stringBuilder.toString());
                            mPresenter.delShoppingCarts(stringBuilder.toString());
                        }
                    }).setPositiveButton(R.string.cancel, R.drawable.button_dialog_transparent, R.color.main_body_major_color, null).create();
            mDialog.show();
        } else {
            mDialog = new CustomDialog.Builder(TreasureFragment.this.getActivity())
                    .setMessage(R.string.shopping_del_empty_prompt)
                    .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white, null).create();
            mDialog.show();
        }
    }

    private void submitOrder() {
        boolean isSelect = false;
        boolean isError = false;
        if (null != this.getActivity()) {
            if (!NetworkUtil.isAvailable(this.getActivity())) {
                ToastUtil.showTip(TreasureFragment.this.getActivity(), R.string.network_error);
                return;
            }
        }
        ArrayList<ShoppingCartResp.DataBean> list = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).isClick) {
                isSelect = true;
                ShoppingCartResp.DataBean bean = mList.get(i);
                if (mList.get(i).isClick) {
                    list.add(mList.get(i));
                }
                if (bean.stock <= 0 || bean.status != 1) {
                    isError = true;
                }
            }
        }
        if (!isSelect) {
            mDialog = new CustomDialog.Builder(TreasureFragment.this.getActivity())
                    .setMessage(R.string.shopping_empty_commodity_prompt)
                    .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white, null).create();
            mDialog.show();
        } else if (isError) {
            mDialog = new CustomDialog.Builder(TreasureFragment.this.getActivity())
                    .setMessage(R.string.shopping_commodity_error_prompt)
                    .setNegativeButton(R.string.confirm, R.drawable.button_dialog_green, R.color.white, null).create();
            mDialog.show();
        } else {
            ARouter.getInstance().build("/xy/order/submit")
                    .withObject("list", list)
                    .navigation();
        }
    }

    private void selectAll() {
        if (mCheckSelectAll.isChecked()) {
            if (null != mList) {
                for (int i = 0; i < mList.size(); i++) {
                    ShoppingCartResp.DataBean bean = mList.get(i);
                    bean.isClick = true;
                }
                mAdapter.notifyDataSetChanged();
            }
        } else {
            if (null != mList) {
                for (int i = 0; i < mList.size(); i++) {
                    ShoppingCartResp.DataBean bean = mList.get(i);
                    bean.isClick = false;
                }
                mAdapter.notifyDataSetChanged();
            }
        }
        updateBottomBarAndCheck();
    }

    private void updateBottomBarAndCheck() {
        updateBottomBar();
        if (null != mList && mList.size() > 0) {
            int size = 0;
            for (int i = 0; i < mList.size(); i++) {
                if (mList.get(i).isClick) {
                    size++;
                }
            }
            mCheckSelectAll.setChecked(size == mList.size());
        } else {
            mCheckSelectAll.setChecked(false);
        }
    }

    private void updateBottomBar() {
        if (null != mList) {
            if (mList.size() == 0) {
                Timber.e("mList=" + mList);
                showText("合   计: 0.00元 (含运费: 0.00元)", "共0件商品 ");
            } else {
                BigDecimal price = new BigDecimal("0");
                int num = 0;
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).isClick) {
                        num++;
                        ShoppingCartResp.DataBean bean = mList.get(i);
                        Timber.e("bean=" + bean);
                        price = price.add(bean.price.multiply(bean.amount));
                    }
                }
                String totalPrice = "合   计: " + NumberFormatUtils.getInstance().format2Decimal(price.doubleValue()) + "元" + "(含运费: 0.00元)";
                String totalNum = "共" + num + "件商品";
                showText(totalPrice, totalNum);
            }
        } else {
            showText("合   计: 0.00元 (含运费: 0.00元)", "共0件商品 ");
        }
    }

    private void showText(String totalPrice, String totalNum) {
        mTextTotalNum.setText(totalNum);
        if (null != this.getActivity()) {
            setTextValue(mTextTotalPrice, totalPrice, ContextCompat.getColor(this.getActivity(), R.color.aid_prompt_color), 15, totalPrice.indexOf(":") + 1, totalPrice.lastIndexOf("("));
            setTextValue(mTextTotalPrice, totalPrice, ContextCompat.getColor(this.getActivity(), R.color.aid_prompt_color), 12, totalPrice.indexOf("("), totalPrice.length());
        }
    }

    private void setTextValue(TextView textView, String text, int color, int size, int start, int end) {
        SpannableString spanString = new SpannableString(text);
        //再构造一个改变字体颜色的Span
        ForegroundColorSpan span = new ForegroundColorSpan(color);
        //将这个Span应用于指定范围的字体
        spanString.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        AbsoluteSizeSpan span1 = new AbsoluteSizeSpan(size, true);
        spanString.setSpan(span1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        Timber.d("sizeSpan=" + size);
        textView.setText(spanString);
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }

    @Override
    public void loadTreasureListSuccess(ShoppingCartResp resp) {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mRecyclerTreasure.setVisibility(View.VISIBLE);
        if (null != resp.data) {
            mList.clear();
            mList.addAll(resp.data);
            mAdapter.setNewData(mList);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void loadTreasureListFailure() {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mRecyclerTreasure.setVisibility(View.VISIBLE);
        mList.clear();
        mAdapter.setNewData(mList);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void delShoppingCartSuccess(BaseResp resp, int position) {
        mAdapter.remove(position);
        mAdapter.notifyDataSetChanged();
        updateBottomBarAndCheck();
        // updateShopCartTotal();
    }

    @Override
    public void delShoppingCartsSuccess(BaseResp resp) {
        Iterator<ShoppingCartResp.DataBean> iterator = mList.iterator();
        while (iterator.hasNext()) {
            ShoppingCartResp.DataBean bean = iterator.next();
            if (bean.isClick) {
                iterator.remove();
            }
        }
        mAdapter.notifyDataSetChanged();
        updateBottomBarAndCheck();
        // updateShopCartTotal();
    }

    @Override
    public void delShoppingCartFailure() {
        Timber.tag("TreasureFragment").e("delShoppingCartFailure");
    }

    @Override
    public void updateShopCartSuccess(ShoppingCartUpdateResp resp) {
        Timber.tag("TreasureFragment").e("updateShopCartSuccess resp=" + resp);
    }

    @Override
    public void updateShopCartFailure() {
        Timber.tag("TreasureFragment").e("updateShopCartFailure");
    }

    @Override
    public void onRefresh() {
        ShoppingCartReq req = new ShoppingCartReq();
        mPresenter.loadTreasureList(req);
        mCheckSelectAll.setChecked(false);
    }
}
